import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Router} from '@angular/router';

import {LoginService} from './login.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  public validateForm: FormGroup;
  public login = {username: null, password: null, authcode: null};

  constructor(private fb: FormBuilder, private router: Router, private loginService: LoginService) {
  }

  private checkForm() {
    if (localStorage.token) {
      this.login.username = localStorage.username;
      this.login.password = localStorage.password;
      this.login.authcode = null;
    }
    this.validateForm = this.fb.group({
      username: [this.login.username, [Validators.required, Validators.minLength(4), Validators.maxLength(20)]],
      password: [this.login.password, [Validators.required, Validators.minLength(6), Validators.maxLength(18)]],
      authcode: [this.login.authcode, [Validators.required]]
    });
  }

  private loginCheck() {
    this.loginService.loginCheck(this.validateForm.value).subscribe(res => {
      if (res['status']['errmsg'] === 'success' && res['data']) {
        localStorage.token = res['token'];
        if (this.validateForm.value.remember) {
          localStorage.uid = res['data'][0]['uid'];
          localStorage.username = res['data'][0]['username'];
          localStorage.password = res['data'][0]['password'];
        }
        this.router.navigate(['main']);
      }
    });
  }

  public submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }

    // 登录控制
    if (this.validateForm.status === 'VALID') {
      this.loginCheck();
    }
  }

  ngOnInit() {
    this.checkForm();
  }
}
